const ffi = require('koffi');
const path = require('path');
const { parentPort } = require('worker_threads');

function loadLibrary(currentScaleType) {
    const dllMaps = {
        '1': './sigang/pos_ad_dll.dll',
        '2': './tuoliduo_freshway/pos_ad_dll.dll',
        '3': './tuoliduo_freshstar/pos_ad_dll.dll'
    };
    const dllPath = path.resolve(__dirname, dllMaps[currentScaleType]);
    try {
        return ffi.load(dllPath);
    } catch (e) {
        console.error('Failed to load DLL:', e);
       
    }
}



let tareBuffer = Buffer.alloc(128, 0); //皮重


function sendTare(currentScaleType, weight) {
    try {
        const lib = loadLibrary(currentScaleType);
        let sendTareFunc = lib.func('int send_tare(char *rbuf)')
        
        if (sendTareFunc(weight + '') == 240) {
            let tareVal = tareBuffer.subarray(1, 7).toString('ascii').trim().replace(/[\x00-\x1F]/g, '')
            parentPort.postMessage({ text: 'sendTare', tare: tareVal });

        } else {
            parentPort.postMessage({ text: 'sendTare', isError: true });
        }
    } catch (error) {
        console.log('sendTare error')
        console.log(error)
    }
    
}



async function toPrint(currentScaleType, printDataPath) {

    try {
        const lib = loadLibrary(currentScaleType);
        let printFunc, beginPrintFunc;
        if (currentScaleType === '1') {
            printFunc = lib.func('int PrintBitmap(char* file)');
        } else {
            printFunc = lib.func('int PrintBitmapFile(char* BmpFileName, int LabelAngle)');
            beginPrintFunc = lib.func('int BeginPrint(int PrintType)');
        }

        let res;
        if (currentScaleType === '1') {
            res = printFunc(printDataPath);
        } else {
            res = printFunc(printDataPath, 0);
        }

        if (res !== 240) {
            parentPort.postMessage({ text: 'sendPrint', isError: true });
        }

        if (currentScaleType !== '1') {

            beginPrintFunc(7); // 开始打印
            beginPrintFunc(8); // 切纸


        }
        
    } catch (e) {
        parentPort.postMessage({ text: 'sendPrint', isError: true });
    }
}

parentPort.on('message', ({ text, currentScaleType, weight, printDataPath }) => { //主进程发送过来的消息

    if (text === 'startSendStare') { //去皮
        sendTare(currentScaleType, weight)
    } else if (text === 'startSendZero') { //置零
        sendZero(currentScaleType)
    } else if (text === 'startPrint') { //打印
        toPrint(currentScaleType, printDataPath)
    }
});

//置零
function sendZero(currentScaleType) {
    try {
         const lib = loadLibrary(currentScaleType);
        let sendZeroFunc = lib.func('int send_zero()')
         if (sendZeroFunc() != 240) {
            parentPort.postMessage({ text: 'sendZero', isError: true });
        }
    } catch (error) {
        console.log(error)
    }
    
}

